<template>
  <view v-if="!isLoading" class="container">
    <!-- 快递配送：配送地址 -->

    <!-- 商品列表 -->
    <view class="goods-list i-card">
      <view class="gtitle"> 已购服务</view>
      <view class="goods-item" v-for="(goods, idx) in order.goods" :key="idx">
        <view class="goods-main" @click="handleTargetGoods(goods.goods_id)">
          <!-- 商品图片 -->
          <view class="goods-image">
            <image
              class="image"
              :src="goods.goods_image"
              mode="aspectFill"
            ></image>
          </view>
          <!-- 商品信息 -->
          <view class="goods-content">
            <view class="goods-title"
              ><text class="twoline-hide">{{ goods.goods_name }}</text></view
            >
            <view class="goods-props clearfix" v-if="goods.goods_props">
              <view
                class="goods-props-item"
                v-for="(props, idx) in goods.goods_props"
                :key="idx"
              >
                <text>{{ props.value.name }}</text>
              </view>
            </view>
            <view class="gdesc g0" v-if="order.expiration_time">
              有效期至：{{ order.expiration_time }}
            </view>
            <view class="gdesc"> 预约后，我们将上门为您服务 </view>
          </view>
          <!-- 交易信息 -->
          <view class="goods-trade">
            <view class="goods-price">
              <text class="unit">￥</text>
              <text class="value">{{
                goods.is_user_grade
                  ? goods.grade_goods_price
                  : goods.goods_price
              }}</text>
            </view>
            <view class="goods-num">
              <text>×{{ goods.total_num }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view @click="onSelectAddress" class="flow-delivery">
      <view class="gtitle">您的服务地址</view>
      <view class="flow-delivery__detail dis-flex flex-y-center">
        <view class="detail-location dis-flex">
          <text class="iconfont icon-dingwei"></text>
        </view>
        <view class="detail-content flex-box">
          <block v-if="address">
            <view class="detail-content__title dis-flex">
              <text class="f-30">{{ address.name }}</text>
              <text class="detail-content__title-phone f-28">{{
                address.phone
              }}</text>
            </view>
            <view class="address detail-content__describe">
              <text
                class="region"
                v-for="(region, idx) in address.region"
                :key="idx"
                >{{ region }}</text
              >
              <text class="detail">{{ address.detail }}</text>
              <text class="menpaihao">{{ address.menpaihao }}</text>
            </view>
          </block>
          <block v-else>
            <view class="detail-content__describe dis-flex">
              <text class="col-6">请选择服务地址</text>
            </view>
          </block>
        </view>
        <view class="detail-arrow dis-flex">
          <text class="iconfont icon-arrow-right"></text>
        </view>
      </view>
    </view>
    <!-- 服务时间 -->
    <view class="flow-delivery" @tap="showPicker()">
      <view class="gtitle">预约时间</view>
      <view class="flow-delivery__detail d2 dis-flex flex-y-center">
        <view class="ytime" v-if="dateTime">{{ dateTime }}</view>
        <view class="ytips" v-else>请预约服务时间</view>
        <view class="detail-arrow dis-flex">
          <text class="iconfont icon-arrow-right"></text>
        </view>
        <!-- <text class="flex-five">服务时间：</text>
        <view class="flex-five t-r">
          <view v-if="dateTime == ''" @tap="showPicker()">
            <text class="col-m">选择时间</text>
            <text class="right-arrow iconfont icon-arrow-right"></text>
          </view>

          <view v-else @tap="showPicker()">
            <text class="">{{ dateTime }}</text>
            <text class="col-m">修改</text>
          </view>
        </view> -->
      </view>
      <view class="ytips2">* 并非实际服务时间，具体服务时间请咨询客服</view>
    </view>
    <w-time-picker
      theme="#fa2209"
      ref="picker"
      @confirm="onConfirm"
      @cancel="onCancel"
      :afterDays="10"
      :step="30"
    ></w-time-picker>
    <!-- 底部操作按钮 -->
    <view
      v-if="order.order_status != OrderStatusEnum.CANCELLED.value"
      class="footer-fixed"
    >
      <view class="btn-wrapper">
        <!-- 未支付取消订单 -->
        <view class="btn-item active" @click="onYuyue()">立即预约</view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  DeliveryStatusEnum,
  DeliveryTypeEnum,
  OrderStatusEnum,
  PayStatusEnum,
  PayTypeEnum,
  ReceiptStatusEnum,
} from "@/common/enum/order";
import * as OrderApi from "@/api/order";
import * as CheckoutApi from "@/api/checkout";
import * as AddressApi from "@/api/address";
import { wxPayment } from "@/core/app";
import wTimePicker from "@/components/w-time-picker/w-time-picker.vue";
export default {
  components: {
    wTimePicker,
  },
  data() {
    return {
      // 枚举类
      DeliveryStatusEnum,
      DeliveryTypeEnum,
      OrderStatusEnum,
      PayStatusEnum,
      PayTypeEnum,
      ReceiptStatusEnum,
      // 当前订单ID
      orderId: null,
      orderNo: "",
      amount: 0,
      // 加载中
      isLoading: true,
      // 当前订单详情
      order: {
        // 是否存在收货地址
        existAddress: false,
        // 默认收货地址
        address: null,
        // 是否存在收货地址
        existAddress: false,
      },
      // 当前设置
      setting: {},
      // 支付方式弹窗
      showPayPopup: false,
      mode: 1,
      status: 1,
      refundId: "",
      imId: "hjm616161",
      dateTime: "",
      address: null,
    };
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad({ orderId }) {
    // 当前订单ID
    this.orderId = orderId;
    console.log(this.orderId);
    // 获取当前订单信息
    //this.getOrderDetail()
  },
  onShow() {
    // 获取当前订单信息
    this.getOrderDetail();
  },
  methods: {
    // 快递配送：选择收货地址
    onSelectAddress() {
      this.$navTo("pages/address/index", {
        from: "checkout",
      });
    },
    applyRefund(event) {
      const { orderId } = event.detail;
      const extra = {
        orderId,
      }; // 开发者需要透传的参数，可自定义内容
      return new Promise((resolve) => {
        resolve(extra);
      });
    },

    // bind:refund 使用示例
    handleRefund(event) {
      console.log(event);
      const app = this;
      const { status, result } = event.detail;
      if (status === "success") {
        const { refundId, outRefundNo } = result;

        OrderApi.refund(app.orderId, {
          refundId: refundId,
        }).then((result) => {});
      } else {
        const { errMsg } = result;
      }
    },
    handleError(event) {
      console.log("handleError-event", event.detail);
      const { errNo, errMsg } = event.detail;
    },
    getGoodsInfo(event) {
      console.log("getGoodsInfo-event", event);
      return new Promise((resolve) => {
        // 在此处开发者可以进行商品数据请求，获取商品信息，然后将商品信息传入 resolve 函数
        resolve({
          minLimits: 1,
          maxLimits: 2,
          dateRule: "周一至周日可用",
          relationType: 1,
          validation: {
            phoneNumber: {
              required: true, // 手机号是否必填
            },
            reservationType: 1,
            reservationCount: 2,
          },
          // 在 bind:getgoodsinfo 返回的 promise 的 resolve 函数中新增 marketingVersion 字段
          marketingVersion: 2,
        });
      });
    },
    userLogin(event) {
      console.log("event", event);
      return new Promise((resolve, reject) => {
        tt.login({
          success() {
            // 用户登录成功并获取信息，则调用 resolve 函数，跳转至提单页
            resolve();
          },
          fail() {
            // 用户登录失败，则跳转提单页失败
            reject();
          },
        });
      });
    },
    handleUnrealPay(event) {
      console.log("pay-event: " + event.detail);
      console.log(event);
      const { status, orderId, outOrderNo, result } = event.detail;
      if (status === "success") {
        const { code } = result;
        if (code === 0) {
          console.log("redirectTo调用成功 ", res);
        } else {
          // 支付失败（超时、取消、关闭）
          uni.showToast({
            title: "支付失败，请重试",
            icon: "none",
          });
        }
      } else {
        const { errMsg } = result;
      }
    },
    // 获取当前订单信息
    getOrderDetail() {
      const app = this;
      app.isLoading = true;
      OrderApi.detail(app.orderId).then((result) => {
        console.log(result);
        app.order = result.data.order;
        app.setting = result.data.setting;
        app.orderNo = result.data.order.order_no;
        app.amount = result.data.order.pay_price * 100;
        app.isLoading = false;
        app.refundId = result.data.order.douyin_refund_id;
        if (app.order.delivery_status1 == DeliveryStatusEnum.DELIVERED.value) {
          app.dateTime = app.order.service_time.substr(0, 16);
        }
      });
      AddressApi.getDefault().then((result) => {
        console.log(result);
        app.address = result.data.detail;
      });
    },

    // 复制指定内容
    handleCopy(value) {
      const app = this;
      uni.setClipboardData({
        data: value,
        success() {
          app.$toast("复制成功");
        },
      });
    },

    // 跳转到物流跟踪页面
    handleTargetExpress() {
      this.$navTo("pages/order/express/index", {
        orderId: this.orderId,
      });
    },

    // 跳转到商品详情页面
    handleTargetGoods(goodsId) {
      this.$navTo("pages/goods/detail", {
        goodsId,
      });
    },

    // 跳转到申请售后页面
    handleApplyRefund(orderGoodsId) {
      this.$navTo("pages/refund/apply", {
        orderGoodsId,
      });
    },
    showPicker() {
      this.$refs.picker.show();
    },
    onConfirm(res) {
      this.dateTime = res;
      console.log(res);
    },
    // 取消订单
    onCancel(orderId) {
      const app = this;
      uni.showModal({
        title: "友情提示",
        content: "确认要取消该订单吗？",
        success(o) {
          if (o.confirm) {
            OrderApi.cancel(orderId).then((result) => {
              // 显示成功信息
              app.$toast(result.message);
              // 刷新当前订单数据
              app.getOrderDetail();
            });
          }
        },
      });
    },
    onYuyue() {
      const app = this;
      if (!app.address?.address_id) {
        return app.$toast("请选择服务地址");
      }
      if (!app.dateTime) {
        return app.$toast("请选择服务时间");
      }
      uni.showModal({
        title: "友情提示",
        content: "确定预约吗？",
        success(o) {
          if (o.confirm) {
            CheckoutApi.createbook({
              orderId: app.orderId,
              dateTime: app.dateTime,
              addressId: app.address.address_id,
            })
              .then((result) => {
                // 显示成功信息
                app.$toast(result.message);
                setTimeout(() => {
                  app.onNavigateBack();
                }, 1000);
                // 刷新当前订单数据
                //app.getOrderDetail()
              })
              .catch((result) => {
                app.$error(result.message);
              });
          }
        },
      });
    },
    onNavigateBack(delta = 1) {
      const pages = getCurrentPages();
      if (pages.length > 1) {
        uni.navigateBack({
          delta: Number(delta || 1),
        });
      } else {
        this.$navTo("pages/index/index");
      }
    },
    onRefund(orderId) {
      const app = this;
      uni.showModal({
        title: "友情提示",
        content: "确认要退款吗？",
        success(o) {
          if (o.confirm) {
            OrderApi.refund(orderId)
              .then((result) => {
                // 显示成功信息
                app.$toast(result.message);
                // 刷新当前订单数据
                //app.getOrderDetail()
              })
              .catch((result) => {
                app.$error(result.message);
              });
          }
        },
      });
    },
    // 确认收货
    onReceipt(orderId) {
      const app = this;
      uni.showModal({
        title: "友情提示",
        content: "确认收到商品了吗？",
        success(o) {
          if (o.confirm) {
            OrderApi.receipt(orderId).then((result) => {
              // 显示成功信息
              app.$success(result.message);
              // 刷新当前订单数据
              app.getOrderDetail();
            });
          }
        },
      });
    },

    // 点击去支付
    onPay() {
      // 显示支付方式弹窗
      this.showPayPopup = true;
    },

    // 选择支付方式
    onSelectPayType(payType) {
      const app = this;
      // 隐藏支付方式弹窗
      this.showPayPopup = false;
      // 发起支付请求
      OrderApi.pay(app.orderId, payType)
        .then((result) => app.onSubmitCallback(result))
        .catch((err) => err);
    },

    // 订单提交成功后回调
    onSubmitCallback(result) {
      const app = this;
      // 发起微信支付
      if (result.data.pay_type == PayTypeEnum.WECHAT.value) {
        wxPayment(result.data.payment)
          .then(() => {
            app.$success("支付成功");
            setTimeout(() => {
              app.getOrderDetail();
            }, 1500);
          })
          .catch((err) => {
            app.$error("订单未支付");
          })
          .finally(() => {
            app.disabled = false;
          });
      }
      // 余额支付
      if (result.data.pay_type == PayTypeEnum.BALANCE.value) {
        app.$success("支付成功");
        app.disabled = false;
        setTimeout(() => {
          // 刷新当前订单数据
          app.getOrderDetail();
        }, 1500);
      }
    },

    // 跳转到订单评价页
    handleTargetComment(orderId) {
      this.$navTo("pages/order/comment/index", {
        orderId,
      });
    },
    imCallback(e) {
      console.log("跳转IM客服成功", e.detail);
    },
    onimError(e) {
      console.log("拉起IM客服失败", e.detail);
    },
    phoneclick() {
      tt.makePhoneCall({
        phoneNumber: "4009673811",
        success: function () {},

        fail(err) {
          console.log(err.errMsg);
        },
      });
    },
  },
};
</script>

<style>
page {
  background: #f7fcff;
}
</style>
<style lang="scss" scoped>
.container {
  padding-bottom: constant(env(safe-area-inset-bottom) + 106rpx + 6rpx);
  padding-bottom: calc(env(safe-area-inset-bottom) + 106rpx + 6rpx);
}

// 配送信息
.flow-delivery {
  padding: 34rpx 30rpx;
  margin-top: 20rpx;
  background: #fff;
  background-size: 120rpx auto;

  .detail-location {
    font-size: 36rpx;
  }

  .detail-content {
    padding: 0 20rpx;

    .detail-content__title-phone {
      margin-left: 10rpx;
    }

    .detail-content__describe {
      font-size: 28rpx;
      color: #777;
    }
  }

  .detail-content__title {
    margin-bottom: 6rpx;
  }

  .flow-delivery__detail {
    justify-content: space-between;
    margin-top: 20rpx;
    color: #000;
    font-size: 36rpx;
    .flex-five {
      font-size: 30rpx;
      flex: none;

      .col-m {
        margin-left: 20rpx;
      }
    }
  }
}
.detail-arrow {
  font-size: 42rpx;
  position: relative;
  top: -40rpx;
}
.flow-all-money {
  .ipt-wrapper {
    input {
      font-size: 28rpx;
      width: 100%;
      height: 75rpx;
    }
  }
}
.ytips {
  color: #ccc;
  font-size: 28rpx;
}
.ytips2 {
  color: #f00;
  margin-top: 15rpx;
}
// 页面顶部
.header {
  display: flex;
  justify-content: space-between;
  height: 280rpx;
  padding: 56rpx 30rpx 0 30rpx;

  .order-status {
    display: flex;
    align-items: center;
    height: 128rpx;

    .status-icon {
      width: 128rpx;
      height: 128rpx;

      .image {
        display: block;
        width: 100%;
        height: 100%;
      }
    }

    .status-text {
      padding-left: 20rpx;
      color: #fff;
      font-size: 38rpx;
      font-weight: bold;
    }
  }

  .next-action {
    display: flex;
    align-items: center;
    height: 128rpx;

    .action-btn {
      min-width: 152rpx;
      height: 56rpx;
      padding: 0 30rpx;
      line-height: 56rpx;
      background-color: #fff;
      text-align: center;
      border-radius: 28rpx;
      border-color: rgb(102, 102, 102);
      cursor: pointer;
      user-select: none;
      color: #c7a157;
    }
  }
}

// 通栏卡片
.i-card {
  background: #fff;
  padding: 24rpx 24rpx;
  width: 100%;
  box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
  margin: 0 auto 20rpx auto;
  border-radius: 20rpx;
}

// 收货地址
.delivery-address {
  margin-top: -50rpx;

  .link-man {
    line-height: 46rpx;
    color: #333;

    .name {
      margin-right: 10rpx;
    }
  }

  .address {
    margin-top: 12rpx;
    color: #999;
    font-size: 24rpx;

    .detail {
      margin-left: 6rpx;
    }
  }
}

// 物流公司
.express {
  display: flex;
  align-items: center;

  .main {
    flex: 1;
  }

  .info-item {
    display: flex;
    margin-bottom: 24rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .item-lable {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #999;
      margin-right: 30rpx;
    }

    .item-content {
      flex: 1;
      display: flex;
      align-items: center;
      font-size: 26rpx;
      color: #333;

      .act-copy {
        margin-left: 20rpx;
        padding: 2rpx 20rpx;
        font-size: 22rpx;
        color: #666;
        border: 1rpx solid #c1c1c1;
        border-radius: 16rpx;
      }
    }
  }

  // 右侧箭头
  .right-arrow {
    margin-left: 16rpx;
    // color: #777;
    font-size: 26rpx;
  }
}
.gtitle {
  color: #676666;
  font-size: 34rpx;
  font-weight: normal;
  line-height: 2;
  padding: 0rpx 0rpx;
}
// 商品列表
.goods-list {
  // 商品项
  .goods-item {
    margin-bottom: 40rpx;

    &:last-child {
      margin-bottom: 0;
    }

    // 商品信息
    .goods-main {
      position: relative;
      display: flex;
    }

    // 商品图片
    .goods-image {
      width: 180rpx;
      height: 180rpx;

      .image {
        display: block;
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
      }
    }

    // 商品内容
    .goods-content {
      flex: 1;
      padding-left: 16rpx;
      display: flex;
      justify-content: space-between;
      flex-direction: column;

      .goods-title {
        width: 80%;
        font-size: 26rpx;
        max-height: 76rpx;
        color: #000;
      }

      .goods-props {
        margin-top: 14rpx;
        height: 40rpx;
        color: #ababab;
        font-size: 24rpx;
        overflow: hidden;

        .goods-props-item {
          display: inline-block;
          margin-right: 14rpx;
          padding: 4rpx 16rpx;
          border-radius: 12rpx;
          background-color: #f5f5f5;
          width: auto;
        }
      }
      .gdesc {
        color: #f00;
        font-size: 28rpx;
        &.g0 {
          color: #ababab;
        }
      }
    }

    // 交易信息
    .goods-trade {
      position: absolute;
      right: 0;
      top: 0;
      padding-top: 16rpx;
      width: 150rpx;
      text-align: right;
      color: $uni-text-color-grey;
      font-size: 26rpx;

      .goods-price {
        vertical-align: bottom;
        margin-bottom: 16rpx;

        .unit {
          margin-right: -2rpx;
          font-size: 24rpx;
        }
      }
    }

    // 商品售后
    .goods-refund {
      display: flex;
      justify-content: flex-end;

      .stata-text {
        font-size: 24rpx;
        color: #999;
      }

      .action-btn {
        border-radius: 28rpx;
        padding: 8rpx 26rpx;
        font-size: 24rpx;
        color: #383838;
        border: 1rpx solid #a8a8a8;
      }
    }
  }
}

// 订单信息
.order-info {
  .info-item {
    display: flex;
    margin-bottom: 24rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .item-lable {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #999;
      margin-right: 30rpx;
    }

    .item-content {
      flex: 1;
      display: flex;
      align-items: center;
      font-size: 26rpx;
      color: #333;

      .act-copy {
        margin-left: 20rpx;
        padding: 2rpx 20rpx;
        font-size: 22rpx;
        color: #666;
        border: 1rpx solid #c1c1c1;
        border-radius: 16rpx;
      }
    }
  }
}

// 交易信息
.trade-info {
  .info-item {
    display: flex;
    margin-bottom: 24rpx;

    .item-lable {
      font-size: 24rpx;
      color: #999;
      margin-right: 24rpx;
    }

    .item-content {
      flex: 1;
      font-size: 26rpx;
      color: #333;
      text-align: right;
    }
  }

  .divider {
    height: 1rpx;
    background: #f1f1f1;
    margin-bottom: 24rpx;
  }

  .trade-total {
    display: flex;
    justify-content: flex-end;

    .goods-price {
      margin-left: 12rpx;
      vertical-align: bottom;
      color: $uni-text-color-active;

      .unit {
        margin-right: -2rpx;
        font-size: 24rpx;
      }
    }
  }
}

/* 底部操作栏 */

.footer-fixed {
  position: fixed;
  bottom: var(--window-bottom);
  left: 0;
  right: 0;
  z-index: 11;
  box-shadow: 0 -4rpx 40rpx 0 rgba(151, 151, 151, 0.24);
  background: #fff;

  // 设置ios刘海屏底部横线安全区域
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);

  .btn-wrapper {
    height: 106rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 30rpx;
  }

  .btn-item {
    width: 100%;
    border-radius: 16rpx;
    padding: 20rpx 20rpx;
    font-size: 34rpx;
    color: #383838;
    text-align: center;
    border: 1rpx solid #a8a8a8;

    &.active {
      color: #fff;
      border: none;
      background: linear-gradient(to right, #f9211c, #ff6335);
    }
  }
}

// 弹出层-支付方式
.pay-popup {
  padding: 24rpx;

  .title {
    font-size: 30rpx;
    margin-bottom: 50rpx;
    font-weight: bold;
    text-align: center;
  }

  .pop-content {
    min-height: 260rpx;
    padding: 0 10rpx;

    .pay-item {
      padding: 20rpx 35rpx;
      font-size: 28rpx;
      border-bottom: 1rpx solid #f1f1f1;

      &:last-child {
        border-bottom: none;
      }

      .item-left_icon {
        margin-right: 20rpx;
        font-size: 32rpx;

        &.wechat {
          color: #00c800;
        }

        &.balance {
          color: #ff9700;
        }
      }
    }
  }
}

.movable-area {
  // 保持在右下角
  margin-top: 600rpx;
  margin-left: 0rpx;
  height: calc(100vh - 300rpx);
  width: calc(100vw - 150rpx);
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  position: fixed;
  z-index: 99999999;
  pointer-events: none; //此处要加，鼠标事件可以渗透

  .movable-view {
    width: 100rpx;
    height: 100rpx;
    pointer-events: auto; //恢复鼠标事件

    .newProblem {
      width: 100rpx;
      height: 100rpx;
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      background: #ffffff;
      border-radius: 50%;
      border: 1px solid #a6a6a6;

      image {
        width: 30rpx;
        height: 30rpx;
      }

      text {
        margin-top: 10rpx;
        font-size: 20rpx;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #000000;
      }
    }
  }
}

.movable-area1 {
  // 保持在右下角
  margin-top: 700rpx;
  margin-left: 0rpx;
  height: calc(100vh - 400rpx);
  width: calc(100vw - 150rpx);
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  position: fixed;
  z-index: 99999999;
  pointer-events: none; //此处要加，鼠标事件可以渗透

  .movable-view {
    width: 100rpx;
    height: 100rpx;
    pointer-events: auto; //恢复鼠标事件

    .newProblem {
      width: 100rpx;
      height: 100rpx;
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      background: #ffffff;
      border-radius: 50%;
      border: 1px solid #a6a6a6;

      image {
        width: 30rpx;
        height: 30rpx;
      }

      text {
        margin-top: 10rpx;
        font-size: 20rpx;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #000000;
      }
    }
  }
}

//
</style>
